<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.energyId`" :rules="formRules.energyId" class="mb-0px!">
            <el-select
              v-model="row.energyId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
              value-key="id"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.CRM_PRODUCT_UNIT" :value="row.energyUnitId" />
        </template>
      </el-table-column>
      <el-table-column label="报装月用量" prop="count" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="0.001"
              :precision="3"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="变压器类型" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.transformerId`"
            :rules="[
              {
                required: productList.find((item) => item.id === row.energyId)?.name.includes('电'),
                message: '变压器类型不能为空',
                trigger: 'blur'
              }
            ]"
            class="mb-0px!"
          >
            <el-select
              v-show="productList.find((item) => item.id === row.energyId)?.name.includes('电')"
              v-model="row.transformerId"
              clearable
              placeholder="请选择变压器类型"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_TRANSFORMER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加CRM 企业项目信息-能源报装类别</el-button>
  </el-row>
</template>
<script setup lang="ts">
import * as ProductApi from '@/api/crm/product'
import { ProjectApi } from '@/api/crm/project'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

const props = defineProps<{
  projectId: undefined // 客户项目信息id（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  projectId: [{ required: true, message: '客户项目信息id不能为空', trigger: 'blur' }],
  energyId: [{ required: true, message: '能源编号不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const energyValue = ref<ProductApi.ProductVO>()
const productList = ref<ProductApi.ProductVO[]>([]) // 产品列表
/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.projectId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      formData.value = await ProjectApi.getProjectEnergyListByProjectId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    projectId: undefined,
    energyId: undefined,
    energyUnitId: undefined,
    count: undefined,
    transformerId: undefined
  }
  row.projectId = props.projectId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.energyUnitId = product.unit
  }
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
})
</script>
